<template>
  <el-form ref="formRef" :model="form" labelWidth="120px" label-suffix="：">
    <el-form-item label="节点名称">
      <el-input v-model="form.nodeName"></el-input>
    </el-form-item>
    <el-form-item label="节点ID">
      <el-input v-model="form.typeConcatName" disabled/>
    </el-form-item>
    <el-form-item label="日志级别">
      <el-select v-model="form.loglevel"></el-select>
    </el-form-item>
    <el-form-item label="打印头">
      <el-switch v-model="form.displayHeader" active-value="Y" inactive-value="N"/>
    </el-form-item>
    <el-form-item label="限制行">
      <el-switch v-model="form.limitRows" active-value="Y" inactive-value="N"/>
    </el-form-item>
    <el-form-item v-if="form.limitRows === 'Y'" label="限制行数">
      <el-input-number v-model="form.limitRowsNumber" />
    </el-form-item>
    <el-form-item label="字段">
      <el-table :data="form.fields.field" style="width: 100%">
        <el-table-column prop="name" label="名称" width="200">
          <template #default="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item label="写日志">
      <el-input v-model="form.content"></el-input>
    </el-form-item>
  </el-form>
  <dialog-footer @ok="submitForm" @cancel="cancel"/>

</template>

<script setup>
import {defineComponent, ref, onMounted, reactive, watch} from 'vue';
import {flowServiceStore} from '@data/store/flow';
import {getCommonStepInputFields} from '@data/api/data/dataDevelopment'


const flowCount = flowServiceStore();
import {storeToRefs} from 'pinia';

const {graph, flowData} = storeToRefs(flowCount);

defineComponent({
  name: 'WriteToLog',
});
const props = defineProps({
  detailObject: {
    type: Object,
    default: () => {
    },
  },
})

const form = reactive({
  nodeName: '',
  name: '',
  type: 'WriteToLog',
  distribute: 'Y',
  copies: 1,
  loglevel: '',
  displayHeader: '',
  limitRows: '',
  limitRowsNumber: 0,
  fields: {
    field: []
  },
  content: '',

  GUI: {
    xloc: 1,
    yloc: 1,
    draw: 'Y'
  }
});


const emit = defineEmits(['cancel']);

onMounted(() => {
  form.nodeName = flowData.value[props.detailObject.id]?.nodeName || props.detailObject.data.label;
  form.loglevel = flowData.value[props.detailObject.id]?.loglevel || '';
  form.displayHeader = flowData.value[props.detailObject.id]?.displayHeader || '';
  form.limitRows = flowData.value[props.detailObject.id]?.limitRows || '';
  form.limitRowsNumber = flowData.value[props.detailObject.id]?.limitRowsNumber || 0;
  form.fields = flowData.value[props.detailObject.id]?.fields || {};
  form.content = flowData.value[props.detailObject.id]?.content || '';
  form.name = props.detailObject.id;
  form.typeConcatName = `${props.detailObject.id}(${form.type}-${props.detailObject.id})`;

  form.distribute = flowData.value[props.detailObject.id]?.distribute || 'Y';

  const params = {
    ktrJsonContent: JSON.stringify(setData()),
    stepName: "写日志"
  }
  getCommonStepInputFields(params).then(res => {
    console.log(res)
    if (res.data?.length) {
      form.fields.field = res.data.map((item, index) => ({
        ...(form.fields.field[index] || {}), // 保留原有字段的其他属性
      }))
    } else {
      form.fields = {}
    }
  })
})

const setData = () => {

  let arr = graph.value.toJSON().cells.filter(item => item.shape != "edge" && item.shape != 'start-node' && item.shape != 'end-node');

  arr = arr.map(element => {
    return {
      // ...element,
      name: element.data.label,
      type: element.data.component,
      id: element.id,
      ...flowData.value[element.id]
    }
  })

  let lineArr = graph.value.toJSON().cells.filter(item =>
      item.shape == "edge" &&
      graph.value.toJSON().cells.find(e => e.id == item.source.cell).shape != "start-node" &&
      graph.value.toJSON().cells.find(e => e.id == item.target.cell).shape != 'end-node'
  );


  let hop = [];
  lineArr.map(item => {
    console.log("item",item);
    console.log("flowData",flowData.value);
    hop.push({
      from: flowData.value[item.source.cell]?.name,
      to: flowData.value[item.target.cell]?.name,
      enabled: 'Y'
    })
  })


  let connection = arr.map(item => {
    return {
      name: item.connection,
    }
  }).filter(item => item.name) // 过滤掉name为undefined/null/空的情况

  let uniqueArray = Object.values(connection.reduce((acc, cur) => {
    if (cur.name) { // 增加有效性判断
      acc[cur.name] = cur; // 如果存在相同的name，则后一个会覆盖前一个，保证了唯一性
    }
    return acc;
  }, {}));
  console.log("uniqueArray", uniqueArray)

  let obj = {
    transformation: {
      ...(uniqueArray.length > 0 && { connection: uniqueArray.length === 1 ? uniqueArray[0] : uniqueArray }),
      // connection: uniqueArray.length == 1 ? uniqueArray[0] : uniqueArray,
      order: {
        hop: arr.length == 1 ?
            {
              "from": arr[0].name,
              "to": arr[1].name,
              "enabled": "Y"
            } : hop//transformData(arr),
      },
      step: arr
    }
  }
  return obj;
}

const submitForm = () => {

  flowCount.setFlowData(
      {
          ...flowData.value,
          [props.detailObject.id]: {
              ...form,
              name: `${form.type}-${form.name}`,
          }
      }
  )
  // 触发数据更新事件
  // emit('update-data', {
  //   id: props.detailObject.id,
  //   data: form
  // });
  console.log("flowData",flowData.value);
  emit('cancel');
}

const cancel = () => {
  emit('cancel');
}

const toReader = () => {

}

const parseSql = () => {
}

const deleteField = () => {
  console.log('deleteField');
}

</script>

<style>

</style>